package com.glory.brepda.activity.mfg;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.PublicAuditListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.PackageDetailListEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class OuterBoxCheckActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etJobNo)
    FreeUI_ClearEditText etJobNo;
    @BindView(R.id.etLotID)
    FreeUI_ClearEditText etLotID;
    @BindView(R.id.etOuterBoxID)
    FreeUI_ClearEditText etOuterBoxID;
    @BindView(R.id.etInnerBoxID)
    FreeUI_ClearEditText etInnerBoxID;
    @BindView(R.id.tvAdd)
    TextView tvAdd;
    @BindView(R.id.rvMaterielList)
    RecyclerView rvMaterielList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvQty)
    TextView tvQty;
    @BindView(R.id.tvPackMainQty)
    TextView tvPackMainQty;
    @BindView(R.id.tvMainQty)
    TextView tvMainQty;
    @BindView(R.id.tvBoxQty)
    TextView tvBoxQty;
    @BindView(R.id.tvDaiQty)
    TextView tvDaiQty;
    private PublicAuditListAdapter mPublicAuditListAdapter;
    private PackageDetailListEntity body;
    private int mainQty = 0;
    private int packMainQty = 0;
    private boolean isSubmit = true;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    etOuterBoxID.requestFocus();
                    break;
                case 2:
                    etInnerBoxID.requestFocus();
                    break;
            }
        }
    };

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_outer_box_check;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        initRecyclerView(rvMaterielList, this);
        mPublicAuditListAdapter = new PublicAuditListAdapter(null, false, "boxCheck");
        mPublicAuditListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mPublicAuditListAdapter.isFirstOnly(true);
        rvMaterielList.setAdapter(mPublicAuditListAdapter);

        initEditNotToUpperCase(etLotID, s -> {
            if (s.contains("/CLEANCASEID") || s.contains("/cleanCaseId")){
                etOuterBoxID.setText("");
                etLotID.setText(getText(etLotID).split("/")[0]);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        etOuterBoxID.requestFocus();
                    }
                }, 500);
                return;
            }
            Message message = Message.obtain();
            message.what = 1;
            handler.sendMessageDelayed(message, 500);
        });

        initEditNotToUpperCase(etOuterBoxID, s -> {
            if (s.contains("/CLEANCASEID") || s.contains("/cleanCaseId")){
                etOuterBoxID.setText("");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        etOuterBoxID.requestFocus();
                    }
                }, 500);
                return;
            }
            Message message = Message.obtain();
            message.what = 2;
            handler.sendMessageDelayed(message, 500);
        });

        initEditNotToUpperCase(etInnerBoxID, new editTextListener() {
            @Override
            public void onTextChangeListener(String s) {

                if (s.contains("/CLEANCASEID") || s.contains("/cleanCaseId")){
                    etOuterBoxID.setText("");
                    etInnerBoxID.setText(getText(etInnerBoxID).split("/")[0]);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            etOuterBoxID.requestFocus();
                        }
                    }, 500);
                    return;
                }
                Message message = Message.obtain();
                message.what = 2;
                handler.sendMessageDelayed(message, 500);

                if (getText(etLotID).equals("") || getText(etOuterBoxID).equals("")) {
                    showToast("批次号或外箱ID不能为空", false);
                    etInnerBoxID.setText("");
                    return;
                }

                FreeUI_EntityCallBack<BaseResponseBean<PackageDetailListEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<PackageDetailListEntity>>
                        (new TypeToken<BaseResponseBean<PackageDetailListEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<PackageDetailListEntity>> response) {
                        super.onSuccess(response);
                        body = response.body().getResponse().getBody();
                        publicAudit("APPROVE", getText(etLotID), getText(etInnerBoxID), getText(etOuterBoxID));

                    }

                    @Override
                    public void onError(Response<BaseResponseBean<PackageDetailListEntity>> response) {
                        super.onError(response);

                    }
                };
                JsonObject map = new JsonObject();
                map.addProperty("ACTION_TYPE", "QUERY");
                map.addProperty("CHECKPACKLOTID", s);
                map.addProperty("LOT_ID", getText(etLotID));
                NetUtils.requestPostNet("IF.LBLAPPROVE", "Common", OuterBoxCheckActivity.this, map, callBack);

            }
        });
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit15"))return;

                if (mPublicAuditListAdapter.getData().size() <= 0) {
                    showToast("请先添加核对信息", false);
                    return;
                }

                LotUtils.publicAudit(this, getSupportFragmentManager(), "CASE", "CASE", mPublicAuditListAdapter.getData());
                break;
//            case R.id.tvAdd:
//                if (getText(etLotID).equals("") || getText(etOuterBoxID).equals("")){
//                    showToast("批次号或外箱ID不能为空",false);
//                    return;
//                }
//
//                LotUtils.publicAudit(this, getSupportFragmentManager(), getText(etLotID), getText(etOuterBoxID), "CASE", new LotUtils.netCallback<PackageDetailListEntity>() {
//                    @Override
//                    public void onSuccess(PackageDetailListEntity response) {
//                        if (isHavePackID(response)){
//                            mPublicAuditListAdapter.addData(response);
//                            etLotID.setText("");
//                            etOuterBoxID.setText("");
//                        }
//                    }
//
//                    @Override
//                    public void onFail(Throwable t) {
//                        loadError(t,"PUBLICAUDIT");
//                    }
//                });
//                break;
        }

    }

    private boolean isHavePackID(PackageDetailListEntity response) {
        if (mPublicAuditListAdapter.getData().size() <= 0) {
            return true;
        }

        for (PackageDetailListEntity entity : mPublicAuditListAdapter.getData()) {
            if (entity.getPACKLOTID().equals(response.getPACKLOTID())) {
                showToast("当前包装条码已在列表中", true);
                return false;
            }
        }

        return true;
    }

    private void publicAudit(String ACTION_TYPE, String lotID, String packLotID, String packlotid) {
        FreeUI_EntityCallBack<BaseResponseBean<PackageDetailListEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<PackageDetailListEntity>>
                (new TypeToken<BaseResponseBean<PackageDetailListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<PackageDetailListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(OuterBoxCheckActivity.this, false, getSupportFragmentManager())) {

                    if (isHavePackID(body)) {
                        FreeApi_LogUtils.saveErrorMessages(body.getPACKLOTID(),"activity");
                        PackageDetailListEntity packageDetailListEntity =
                                new PackageDetailListEntity(getText(etInnerBoxID));
                        packageDetailListEntity.setCHECKPACKLOTID(getText(etOuterBoxID));
                        mPublicAuditListAdapter.addData(packageDetailListEntity);
                        tvQty.setText(mPublicAuditListAdapter.getData().size() + "");
                        if (body.getXpackagedetail().getPackageType().equals("BOX")) {
                            mainQty += body.getXpackagedetail().getPackMainQty();
                            packMainQty = body.getXpackagedetail().getPackMainQty();
                            tvPackMainQty.setText(packMainQty+"");
                            tvMainQty.setText(mainQty+"");
                        }

                        ArrayList<String> daiList = new ArrayList<>();
                        ArrayList<String> boxList = new ArrayList<>();
                        for (PackageDetailListEntity data : mPublicAuditListAdapter.getData()) {
                            if (!daiList.contains(data.getPACKLOTID())) {
                                daiList.add(data.getPACKLOTID());
                            }
                            if (!boxList.contains(data.getCHECKPACKLOTID())) {
                                boxList.add(data.getCHECKPACKLOTID());
                            }
                        }
                        tvDaiQty.setText(boxList.size() + "");
                        tvBoxQty.setText(daiList.size() + "");
                        if (!body.getXpackagedetail().getPackageType().equals("BOX")) {
                            mainQty = mainQty - packMainQty;
                            tvMainQty.setText(mainQty + "");
                        }
                        etInnerBoxID.setText("");
                        etInnerBoxID.requestFocus();
                    }
                } else {
                    mainQty = mainQty - packMainQty;
                    tvMainQty.setText(mainQty + "");
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<PackageDetailListEntity>> response) {
                super.onError(response);

            }
        };
        JsonObject map = new JsonObject();
        // L210300005
        // 2109_0000032
        map.addProperty("ACTION_TYPE", ACTION_TYPE);
//        map.addProperty("ACTION_TYPE", "QUERY");
        if (!ACTION_TYPE.equals("QUERY")) {
            map.addProperty("PARENTPACKLOTID", packlotid);
            map.addProperty("LOT_ID", lotID);
            map.addProperty("CHECKTYPE", "caseCheck");
        }
        map.addProperty("CHECKPACKLOTID", packLotID);
        NetUtils.requestPostNet("IF.LBLAPPROVE", "Common", OuterBoxCheckActivity.this, map, callBack);

    }


}
